layui.config({
	base : "js/"
}).use(['form','layer','jquery','laypage','table'],function(){
	var form = layui.form,
		layer = parent.layer === undefined ? layui.layer : parent.layer,
		laypage = layui.laypage,
        table = layui.table,
		$ = layui.jquery;

	//加载页面数据
	function searchData(){
        $.ajax({
            url : "/admin/getMessageInfoByType/3",
            type : "get",
            dataType : "json",
            success : function(resp){
                //执行加载数据的方法
                renderDate(resp.data);
            }
        })
	}
    searchData();

	//添加友情链接
	$(".linksAdd_btn").click(function(){
		var index = layui.layer.open({
			title : "添加大图",
			type : 2,
			content : "/admin/page/bigimage/imageAdd.html",
            end : function(){
                searchData();
            }
		})
		//改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
		$(window).resize(function(){
			layui.layer.full(index);
		})
		layui.layer.full(index);
	})

	//批量删除
	$(".batchDel").click(function(){
		var $checkbox = $('.links_list tbody input[type="checkbox"][name="checked"]');
		var $checked = $('.links_list tbody input[type="checkbox"][name="checked"]:checked');
		if($checkbox.is(":checked")){
			layer.confirm('确定删除选中的信息？',{icon:3, title:'提示信息'},function(index){
				var index = layer.msg('删除中，请稍候',{icon: 16,time:false,shade:0.8});
	            setTimeout(function(){
	            	//删除数据
	            	for(var j=0;j<$checked.length;j++){
	            		for(var i=0;i<linksData.length;i++){
							if(linksData[i].linksId == $checked.eq(j).parents("tr").find(".links_del").attr("data-id")){
								linksData.splice(i,1);
								fillData(linksData);
							}
						}
	            	}
	            	$('.links_list thead input[type="checkbox"]').prop("checked",false);
	            	form.render();
	                layer.close(index);
					layer.msg("删除成功");
	            },2000);
	        })
		}else{
			layer.msg("请选择需要删除的文章");
		}
	})

	//全选
	form.on('checkbox(allChoose)', function(data){
		var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])');
		child.each(function(index, item){
			item.checked = data.elem.checked;
		});
		form.render('checkbox');
	});

	//通过判断文章是否全部选中来确定全选按钮是否选中
	form.on("checkbox(choose)",function(data){
		var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])');
		var childChecked = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"]):checked')
		data.elem.checked;
		if(childChecked.length == child.length){
			$(data.elem).parents('table').find('thead input#allChoose').get(0).checked = true;
		}else{
			$(data.elem).parents('table').find('thead input#allChoose').get(0).checked = false;
		}
		form.render('checkbox');
	})
 
	//操作
	$("body").on("click",".links_edit",function(){  //编辑
		var _this = this;
        var index = layui.layer.open({
            title : "编辑",
            type : 2,
            content : "/message/editMessage/" + $(_this).data("id")+"?type=3",
            end : function(){
                searchData();
            }
        })
        //改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
        $(window).resize(function(){
            layui.layer.full(index);
        })
        layui.layer.full(index);
	})

	$("body").on("click",".links_del",function(){  //删除
		var _this = $(this);
		layer.confirm('确定删除此栏目？',{icon:3, title:'提示信息'},function(index){

			$.get("/admin/deleteSinglePage/"+$(_this).data("id"),function(resp){
				if(resp.code == '0'){
                    _this.parents("tr").remove();
                    layer.msg(resp.msg);
				}
			});
			// layer.close(index);
		});
	})

	//渲染数据
	function renderDate(data){
		var currData = data;
		var dataHtml = '';
        $(".content").html('');
		if(currData.length != 0){
			for(var i=0;i<currData.length;i++){
				dataHtml += '<tr>'
				+'<td><input type="checkbox" name="checked" lay-skin="primary" lay-filter="choose"></td>'
				+'<td align="left">'+(i+1)+'</td>'
				+'<td>'+(currData[i].imgUrl==null?'暂无图片':'<a  target="_blank" href="'+currData[i].imgUrl+'"><img src="'+currData[i].imgUrl+'"></a>')+'</td>'
				+'<td>'+currData[i].categoryName+'</td>'
				+'<td>'+currData[i].sort+'</td>'
				+'<td>'+currData[i].name+'</td>'
				+'<td>'+ '<div><label class="layui-form-label">图文推荐</label><input type="checkbox" messageId="'+currData[i].messageId+'" lay-skin="switch" lay-filter="recommand" lay-text="ON|OFF" '+ (currData[i].isRecommend=='0'?'checked':'')+'></div>'
					+'</td>'
				+'<td>'+currData[i].updateTime+'</td>'
				+'<td>'
				+  '<a class="layui-btn layui-btn-mini links_edit"  data-id="'+data[i].messageId+'"><i class="layui-icon">&#xe642;</i> 编辑</a>'
				+  '<a class="layui-btn layui-btn-danger layui-btn-mini links_del" data-id="'+data[i].messageId+'"><i class="layui-icon">&#xe640;</i> 删除</a>'
				+'</td>'
				+'</tr>';
			}
		}else{
			dataHtml = '<tr><td colspan="17">暂无数据</td></tr>';
		}
		$(".content").html(dataHtml);
		form.render();
	}
    form.on('select(filterCategory)',function(){
        searchData();
    })

	form.on('switch(recommand)',function(data){
		var messageId = $(data.elem).attr("messageId");
		debugger;
		if(data.elem.checked){
			//不推荐
            $.post({
                url : "/admin/addMessage",
                data : JSON.stringify({"messageId":messageId,"isRecommend":"0"}),
                contentType : "application/json;charset=utf-8", //必须，告诉服务器这是json
                success : function(resp){
                    //layer.close(index);
                    if(resp.code == '0'){
                        layer.msg("推荐成功",{icon :1});
                    }else{
                        layer.msg(resp.msg);
                    }
                }
            });
		} else {
            //改为不推荐
            $.post({
                url : "/admin/addMessage",
                data : JSON.stringify({"messageId":messageId,"isRecommend":"1"}),
                contentType : "application/json;charset=utf-8", //必须，告诉服务器这是json
                success : function(resp){
                    //layer.close(index);
                    if(resp.code == '0'){
                        layer.msg("取消推荐成功",{icon :1});
                    }else{
                        layer.msg(resp.msg);
                    }
                }
            });
		}
	})
})
